package com.zhongxi.guoyuan.fragment.RewardCoinOrder;


import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ListView;

import com.google.gson.Gson;
import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshListView;
import com.zhongxi.guoyuan.R;
import com.zhongxi.guoyuan.adapter.rewardCoinOrder.RewardOrderHasNoApplyAdapter;
import com.zhongxi.guoyuan.application.MyApplication;
import com.zhongxi.guoyuan.base.BaseFragment;
import com.zhongxi.guoyuan.entity.BaseResponse;
import com.zhongxi.guoyuan.entity.rewardcoin.RewardCoinOrderResult;
import com.zhongxi.guoyuan.entity.shopcart.Address;
import com.zhongxi.guoyuan.entity.shopcart.RewardPayResult;
import com.zhongxi.guoyuan.url.Url;
import com.zhongxi.guoyuan.view.rewardCoin.ApplyRewardActivity;

import org.json.JSONArray;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * A simple {@link Fragment} subclass.
 */
public class RewardOrderHasNoApplyFragment extends BaseFragment implements AdapterView.OnItemClickListener, PullToRefreshBase.OnRefreshListener2<ListView>{

    private PullToRefreshListView lvList;
    private List<RewardCoinOrderResult.RewardCoinOrder> mydata = new ArrayList<>();
    private RewardOrderHasNoApplyAdapter adapter;
    private String type;

    private Handler handler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            toPay((int)msg.obj);
        }
    };
    private Map<String, String> map = new HashMap<>();
    private JSONArray info;

    /**
     * 去支付
     */
    private void toPay(int pos) {
        type = "pay";
        String str = "&orderid="+mydata.get(pos).getOrderid()+"&ordertype="+mydata.get(pos).getType();
        getServer(Url.VERIFY_ORDER, null, str, false, null, "get");
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        return inflater.inflate(R.layout.fragment_order_has_no_apply, container, false);
    }

    @Override
    protected void initView() {
        super.initView();
        lvList = (PullToRefreshListView) getView().findViewById(R.id.lvList);
        lvList.setMode(PullToRefreshBase.Mode.BOTH);
    }

    @Override
    protected void initData() {
        super.initData();
        adapter = new RewardOrderHasNoApplyAdapter(context, mydata, handler);
        lvList.setAdapter(adapter);
        getOrder();
    }

    /**
     * 获取返银未支付订单
     */
    private void getOrder() {
        type = "order";
        String str = "&page="+pageNum;
        getServer(Url.REWARD_NOPAY, null, str, false, null, "get");
    }

    @Override
    protected void processSuccessResult(String response) {
        super.processSuccessResult(response);
        Gson gson = new Gson();
        try{
            if("order".equals(type)) {
                RewardCoinOrderResult result = gson.fromJson(response, RewardCoinOrderResult.class);
                if (null != result.getSafeobj() && !"".equals(result.getSafeobj())) {
                    MyApplication.getInstance().setSpValue(result.getSafeobj());
                }

                JSONObject obj = new JSONObject(response);
                info = obj.getJSONArray("data");
                result.setInfo(info);
//                adapter.setInfo(info);
                lvList.onRefreshComplete();
                if (pageNum == 1) {
                    mydata.clear();
                }
                if (result.getData().size() > 0) {
                    mydata.addAll(result.getData());
                }
                adapter.notifyDataSetChanged();
            }else if("pay".equals(type)){
                RewardPayResult response1 = gson.fromJson(response, RewardPayResult.class);
                MyApplication.getInstance().setSpValue(response1.getSafeobj());
                Intent intent = new Intent(context, ApplyRewardActivity.class);
                JSONObject obj = new JSONObject(response);
                try {
                    String shippingaddress = obj.getString("shippingaddress");
                    Address address = gson.fromJson(shippingaddress, Address.class);
                    intent.putExtra("address", address);
                }catch (Exception e){
                    e.printStackTrace();
                    Address address = new Address(false);
                    intent.putExtra("address", address);
                }
                intent.putExtra("data", response);
                startActivity(intent);
            }
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    @Override
    protected void ProcessFailResult(String response) {
        super.ProcessFailResult(response);
        Gson gson = new Gson();
        try{
            BaseResponse result = gson.fromJson(response, BaseResponse.class);
            if(null!=result.getSafeobj()&&!"".equals(result.getSafeobj())){
                MyApplication.getInstance().setSpValue(result.getSafeobj());
            }
            if(1000==result.getCode()){
                showShortToast("等待商家确认");
            }
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    @Override
    protected void initEvent() {
        super.initEvent();
        lvList.setOnItemClickListener(this);
        lvList.setOnRefreshListener(this);
    }

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        if (position-1 == adapter.getmExpandedMenuPos()) {
            adapter.setmExpandedMenuPos(-1);
        } else {
            adapter.setmExpandedMenuPos(position-1);
        }
        adapter.notifyDataSetChanged();
    }

    @Override
    public void onPullDownToRefresh(PullToRefreshBase<ListView> refreshView) {
        pageNum = 1;
        getOrder();
    }

    @Override
    public void onPullUpToRefresh(PullToRefreshBase<ListView> refreshView) {
        pageNum++;
        getOrder();
    }
}
